package com.ruoyi.bom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.bom.config.RequestDataHelper;
import com.ruoyi.bom.domain.TqlStapOutChange;
import com.ruoyi.bom.mapper.TqlStapOutChangeMapper;
import com.ruoyi.bom.service.TqlStapOutChangeService;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.datasource.annotation.Master;
import com.ruoyi.common.datasource.annotation.Slave;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhengcl
 * @since 1.0.0
 */
@Service
public class TqlStapOutChangeServiceImpl implements TqlStapOutChangeService {

    @Autowired
    private TqlStapOutChangeMapper tqlStapOutChangeMapper;

    @Override
    public List<TqlStapOutChange> selectList(Map<String, Object> params) {


        String date = (String) params.get("date");
        int month=0;
        if (StringUtils.isNotBlank(date)) {
            month=DateUtils.getMonth(DateUtils.YYYY_MM_DD,date);
        }
        else {
            Calendar now = Calendar.getInstance();
             month = now.get(Calendar.MONTH) + 1;
        }

        String stapName = (String) params.get("stapName");

        String stapCode = (String) params.get("stapCode");
        List<TqlStapOutChange> dtoList=getStapOutChange(stapCode,stapName,date,month);

        for (TqlStapOutChange change : dtoList) {
            change.setDeptname(this.getDeptName(change.getDeptId()));
        }
        return dtoList;
    }



@Slave
    public List<TqlStapOutChange> getStapOutChange(String stapCode,String stapName,String date,int month)
    {
        QueryWrapper<TqlStapOutChange> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(stapCode), "stap_code", stapCode);
        wrapper.apply(StringUtils.isNotBlank(date),"date_format(createtime, '%Y-%m-%d') ='" + date + "'");
        wrapper.like(StringUtils.isNotBlank(date),"stap_name" ,stapName);

        int finalMonth = month;
        RequestDataHelper.setRequestData(new HashMap<String, Object>() {{
            put("index", finalMonth);
        }});
        List<TqlStapOutChange> dtoList = tqlStapOutChangeMapper.selectList(wrapper);
        return dtoList;
    }








    @Override
    @Master
    public String getDeptName(Long deptId) {
       return tqlStapOutChangeMapper.getDeptNameById(deptId);
    }
}
